Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [37]:
# Load pickled data
import pickle
import numpy as np
from sklearn.utils import shuffle
# TODO: Fill this in based on where you saved the training and testing data

training_file = './data/train.p'
validation_file= './data/valid.p'
testing_file = './data/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

In [27]:
y_test_origin[0]
Out[27]:
16

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
import pandas as pd
classLabelList = pd.read_csv('signnames.csv')
classLabelList.keys()
Out[2]:
Index(['ClassId', 'SignName'], dtype='object')
In [3]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = X_train.shape[0]

# TODO: Number of validation examples
n_validation = X_valid.shape[0]

# TODO: Number of testing examples.
n_test = X_test.shape[0]

# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:]

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_validation)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [39]:
### Count the instance number for difference classes.
unique_class, unique_count = np.unique(y_train, return_counts=True)
train_sortedLabels = np.argsort(unique_count)

unique_class_test, unique_count_test = np.unique(y_test, return_counts=True)
test_sortedLabels = np.argsort(unique_count_test)
print(unique_count)
print(train_sortedLabels[unique_class])
[ 180 1980 2010 1260 1770 1650  360 1290 1260 1320 1800 1170 1890 1920
  690  540  360  990 1080  180  300  270  330  450  240 1350  540  210
  480  240  390  690  210  599  360 1080  330  180 1860  270  300  210
  210]
[ 0 37 19 32 27 41 42 24 29 39 21 40 20 36 22  6 16 34 30 23 28 26 15 33
 14 31 17 18 35 11  3  8  7  9 25  5  4 10 38 12 13  1  2]
In [40]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
In [44]:
# draw the max size picture for training and testing
print("Top Three Maximum count Samples:")
fg, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 10))

class_id = train_sortedLabels[-1]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax1.imshow(X_train[train_index])
ax1.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==class_id].SignName.to_string(header=False,index=False)
ax1.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)

class_id = train_sortedLabels[-2]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax2.imshow(X_train[train_index])
ax2.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax2.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)

class_id = train_sortedLabels[-3]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax3.imshow(X_train[train_index])
ax3.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax3.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)


plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)

plt.show()

### We also plot bottom three least example images:
print("Bottom three least example images:")
fg, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 10))

class_id = train_sortedLabels[0]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax1.imshow(X_train[train_index])
ax1.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==class_id].SignName.to_string(header=False,index=False)
ax1.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)

class_id = train_sortedLabels[1]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax2.imshow(X_train[train_index])
ax2.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax2.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)

class_id = train_sortedLabels[2]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax3.imshow(X_train[train_index])
ax3.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax3.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription:  %s'%(class_id, train_description), fontsize=8)


plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)

plt.show()
Top Three Maximum count Samples:
Bottom three least example images:
In [7]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.

def labelset_info(labelsettxt, dataset):
    # get stats for the labels
    labelset = dataset['labels']
    labelStats = pd.DataFrame(labelset)
   
#     print(labelsettxt, "set label stats:")
#     print(labelStats.describe())
   
    labelsInfo = {}
    modeCount = 0
    modeLabel = 0
    for i in range(len(labelset)):
        # for each label
        label = str(labelset[i])
      
        # try to see if there is a hash hit
        labelInstance = labelsInfo.get(label, {'count': 0, 'samples':[]})
      
        # add to the count
        count = labelInstance['count'] + 1
      
        # add to samples
        samples = labelInstance['samples']
        samples.append(i)
    
      # put in the last Index
        labelsInfo[label] = {'lastIdx':i, 'count': count, 'label':int(label), 'samples':samples}
      
        # update most common size
        if count > modeCount:
            modeCount = count 
            modeSize = labelsInfo[label]
    
    # get the list of counts and sort them
    sortedLabels = list(labelsInfo.keys())
   
    def compare_count(label):
        return labelsInfo[label]['count']
   
    sortedLabels.sort(key=compare_count)

    # get the unique number of original picture sizes and the min and max last instance
    n_labels = len(sortedLabels)
    minLabel = sortedLabels[0]
    maxLabel = sortedLabels[n_labels-1]

    # print the stats
    print("\nNumber of unique labels in", labelsettxt,"set: ", n_labels)

    print("\nDistribution of", labelsettxt, "set labels:")
    for n in range(n_labels):
        i = sortedLabels[n_labels-n-1]
        classId = labelsInfo[str(i)]['label']
        index = labelsInfo[str(i)]['lastIdx']
        count = labelsInfo[str(i)]['count']
        description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
        print(labelsettxt, " set count: {0:4d}  ClassId: {1:02d}  Description: {2}".format(count, classId, description))

    return n_labels, sortedLabels, labelsInfo, minLabel, maxLabel, modeLabel

train_labels, train_sortedLabels, train_labelInfo, train_minLabel, train_maxLabel, train_modeLabel = labelset_info("training", train)
test_labels, test_sortedLabels, test_labelInfo, test_minLabel, test_maxLabel, test_modeLabel = labelset_info("testing", test)
Number of unique labels in training set:  43

Distribution of training set labels:
training  set count: 2010  ClassId: 02  Description: Speed limit (50km/h)
training  set count: 1980  ClassId: 01  Description: Speed limit (30km/h)
training  set count: 1920  ClassId: 13  Description: Yield
training  set count: 1890  ClassId: 12  Description: Priority road
training  set count: 1860  ClassId: 38  Description: Keep right
training  set count: 1800  ClassId: 10  Description: No passing for vehicles over 3.5 metric tons
training  set count: 1770  ClassId: 04  Description: Speed limit (70km/h)
training  set count: 1650  ClassId: 05  Description: Speed limit (80km/h)
training  set count: 1350  ClassId: 25  Description: Road work
training  set count: 1320  ClassId: 09  Description: No passing
training  set count: 1290  ClassId: 07  Description: Speed limit (100km/h)
training  set count: 1260  ClassId: 08  Description: Speed limit (120km/h)
training  set count: 1260  ClassId: 03  Description: Speed limit (60km/h)
training  set count: 1170  ClassId: 11  Description: Right-of-way at the next intersection
training  set count: 1080  ClassId: 18  Description: General caution
training  set count: 1080  ClassId: 35  Description: Ahead only
training  set count:  990  ClassId: 17  Description: No entry
training  set count:  690  ClassId: 14  Description: Stop
training  set count:  690  ClassId: 31  Description: Wild animals crossing
training  set count:  599  ClassId: 33  Description: Turn right ahead
training  set count:  540  ClassId: 15  Description: No vehicles
training  set count:  540  ClassId: 26  Description: Traffic signals
training  set count:  480  ClassId: 28  Description: Children crossing
training  set count:  450  ClassId: 23  Description: Slippery road
training  set count:  390  ClassId: 30  Description: Beware of ice/snow
training  set count:  360  ClassId: 06  Description: End of speed limit (80km/h)
training  set count:  360  ClassId: 34  Description: Turn left ahead
training  set count:  360  ClassId: 16  Description: Vehicles over 3.5 metric tons prohibited
training  set count:  330  ClassId: 22  Description: Bumpy road
training  set count:  330  ClassId: 36  Description: Go straight or right
training  set count:  300  ClassId: 20  Description: Dangerous curve to the right
training  set count:  300  ClassId: 40  Description: Roundabout mandatory
training  set count:  270  ClassId: 21  Description: Double curve
training  set count:  270  ClassId: 39  Description: Keep left
training  set count:  240  ClassId: 24  Description: Road narrows on the right
training  set count:  240  ClassId: 29  Description: Bicycles crossing
training  set count:  210  ClassId: 27  Description: Pedestrians
training  set count:  210  ClassId: 32  Description: End of all speed and passing limits
training  set count:  210  ClassId: 42  Description: End of no passing by vehicles over 3.5 metric ...
training  set count:  210  ClassId: 41  Description: End of no passing
training  set count:  180  ClassId: 00  Description: Speed limit (20km/h)
training  set count:  180  ClassId: 19  Description: Dangerous curve to the left
training  set count:  180  ClassId: 37  Description: Go straight or left

Number of unique labels in testing set:  43

Distribution of testing set labels:
testing  set count:  750  ClassId: 02  Description: Speed limit (50km/h)
testing  set count:  720  ClassId: 13  Description: Yield
testing  set count:  720  ClassId: 01  Description: Speed limit (30km/h)
testing  set count:  690  ClassId: 12  Description: Priority road
testing  set count:  690  ClassId: 38  Description: Keep right
testing  set count:  660  ClassId: 10  Description: No passing for vehicles over 3.5 metric tons
testing  set count:  660  ClassId: 04  Description: Speed limit (70km/h)
testing  set count:  630  ClassId: 05  Description: Speed limit (80km/h)
testing  set count:  480  ClassId: 09  Description: No passing
testing  set count:  480  ClassId: 25  Description: Road work
testing  set count:  450  ClassId: 08  Description: Speed limit (120km/h)
testing  set count:  450  ClassId: 03  Description: Speed limit (60km/h)
testing  set count:  450  ClassId: 07  Description: Speed limit (100km/h)
testing  set count:  420  ClassId: 11  Description: Right-of-way at the next intersection
testing  set count:  390  ClassId: 35  Description: Ahead only
testing  set count:  390  ClassId: 18  Description: General caution
testing  set count:  360  ClassId: 17  Description: No entry
testing  set count:  270  ClassId: 31  Description: Wild animals crossing
testing  set count:  270  ClassId: 14  Description: Stop
testing  set count:  210  ClassId: 15  Description: No vehicles
testing  set count:  210  ClassId: 33  Description: Turn right ahead
testing  set count:  180  ClassId: 26  Description: Traffic signals
testing  set count:  150  ClassId: 06  Description: End of speed limit (80km/h)
testing  set count:  150  ClassId: 28  Description: Children crossing
testing  set count:  150  ClassId: 30  Description: Beware of ice/snow
testing  set count:  150  ClassId: 23  Description: Slippery road
testing  set count:  150  ClassId: 16  Description: Vehicles over 3.5 metric tons prohibited
testing  set count:  120  ClassId: 36  Description: Go straight or right
testing  set count:  120  ClassId: 22  Description: Bumpy road
testing  set count:  120  ClassId: 34  Description: Turn left ahead
testing  set count:   90  ClassId: 42  Description: End of no passing by vehicles over 3.5 metric ...
testing  set count:   90  ClassId: 39  Description: Keep left
testing  set count:   90  ClassId: 40  Description: Roundabout mandatory
testing  set count:   90  ClassId: 29  Description: Bicycles crossing
testing  set count:   90  ClassId: 24  Description: Road narrows on the right
testing  set count:   90  ClassId: 20  Description: Dangerous curve to the right
testing  set count:   90  ClassId: 21  Description: Double curve
testing  set count:   60  ClassId: 37  Description: Go straight or left
testing  set count:   60  ClassId: 00  Description: Speed limit (20km/h)
testing  set count:   60  ClassId: 19  Description: Dangerous curve to the left
testing  set count:   60  ClassId: 41  Description: End of no passing
testing  set count:   60  ClassId: 32  Description: End of all speed and passing limits
testing  set count:   60  ClassId: 27  Description: Pedestrians
In [8]:
from tqdm import tqdm
import time
from matplotlib import gridspec

def draw_sample_labelsets(datasettxt, sortedlabels, labeldata, dataset, n_samples=10, cmap=None):
    
    n_labels = len(sortedlabels)
    
    # size of each sample
    fig = plt.figure(figsize=(n_samples*1.8, n_labels))
    w_ratios = [1 for n in range(n_samples)]
    w_ratios[:0] = [int(n_samples*0.8)]
    h_ratios = [1 for n in range(n_labels)]

    # gridspec
    time.sleep(1) # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_samples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
    labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
    for a in labelset_pbar:
        classId = labeldata[str(sortedlabels[n_labels-a-1])]['label']
        description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
        count = labeldata[str(sortedlabels[n_labels-a-1])]['count']
        for b in range(n_samples+1):
            i = a*(n_samples+1) + b
            ax = plt.Subplot(fig, grid[i])
            if b == 0:
                ax.annotate('ClassId %d (%d): %s'%(classId, count, description), xy=(0,0), xytext=(0.0,0.5))
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
            else:
                random_i = np.random.choice(labeldata[str(sortedlabels[n_labels-a-1])]['samples'])
                image = dataset[random_i]
                if cmap == None:
                    ax.imshow(image)
                else:
                    # yuv = cv2.split(image)
                    # ax.imshow(yuv[0], cmap=cmap)
                    ax.imshow(image, cmap=cmap)
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
    
        # hide the borders\
        if a == (n_labels-1):
            all_axes = fig.get_axes()
            for ax in all_axes:
                for sp in ax.spines.values():
                    sp.set_visible(False)

    plt.show()

draw_sample_labelsets('Train set sample images (RGB)', train_sortedLabels, train_labelInfo, X_train)
draw_sample_labelsets('Test set sample images (RGB)', test_sortedLabels, test_labelInfo, X_test)
Train set sample images (RGB): 100%|██████████| 43/43 [00:12<00:00,  3.48labels/s]
Test set sample images (RGB): 100%|██████████| 43/43 [00:13<00:00,  3.31labels/s]
In [9]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
def my_reverse(list):
    newlist = []
    for n in list:
        newlist[:0] = [n]
    return newlist

# Plot bar graph of class id count distribution
n_labels = len(train_sortedLabels)
training_labels = my_reverse(train_sortedLabels)
training_counts = [train_labelInfo[n]['count'] for n in training_labels]
training_percantage = training_counts / np.sum(training_counts)
testing_counts = [test_labelInfo[n]['count'] for n in training_labels]
test_percantage = testing_counts / np.sum(testing_counts)

ind = np.arange(n_labels)
width = 0.35

fg, ax = plt.subplots(figsize=(n_labels/2, 10))
rects1 = ax.bar(ind+1, training_percantage, width, color='g')
rects2 = ax.bar(ind+1+width, test_percantage, width, color='r')

# add some text for labels, title and axes ticks
ax.set_ylabel("Percantage", fontsize=20)
ax.set_title("Percantage by datasets and class ids", fontsize=20)
ax.set_xticks(ind + width+1.0)
ax.set_xticklabels(training_labels, fontsize=12)
ax.set_xlabel("Class Id", fontsize=20)

ax.legend((rects1[0], rects2[0]), ('Training', 'Testing'))
plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [10]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
X_train = (X_train - 128) / 128
X_valid = (X_valid - 128) / 128
X_test = (X_test - 128) / 128


from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)

Model Architecture

In [7]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

# Here we use LeNet 5 archecture

import tensorflow as tf
from models import LeNet
/home/stevenwudi/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
WARNING:tensorflow:From /home/stevenwudi/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Use the retry module or similar alternatives.

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [8]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.


x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
In [12]:
rate = 0.001

logits = LeNet(x, n_classes)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

# Model evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
WARNING:tensorflow:From <ipython-input-12-a764b1364a54>:4: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:

Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See tf.nn.softmax_cross_entropy_with_logits_v2.

In [16]:
EPOCHS = 100
BATCH_SIZE = 128


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        training_accuracy = evaluate(X_train, y_train)    
        validation_accuracy = evaluate(X_valid, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Training Accuracy = {:.3f}".format(training_accuracy))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './lenet')
    print("Model saved")
Training...

EPOCH 1 ...
Training Accuracy = 0.443
Validation Accuracy = 0.315

EPOCH 2 ...
Training Accuracy = 0.701
Validation Accuracy = 0.548

EPOCH 3 ...
Training Accuracy = 0.788
Validation Accuracy = 0.627

EPOCH 4 ...
Training Accuracy = 0.843
Validation Accuracy = 0.670

EPOCH 5 ...
Training Accuracy = 0.877
Validation Accuracy = 0.686

EPOCH 6 ...
Training Accuracy = 0.900
Validation Accuracy = 0.715

EPOCH 7 ...
Training Accuracy = 0.910
Validation Accuracy = 0.716

EPOCH 8 ...
Training Accuracy = 0.939
Validation Accuracy = 0.741

EPOCH 9 ...
Training Accuracy = 0.953
Validation Accuracy = 0.751

EPOCH 10 ...
Training Accuracy = 0.955
Validation Accuracy = 0.739

EPOCH 11 ...
Training Accuracy = 0.958
Validation Accuracy = 0.733

EPOCH 12 ...
Training Accuracy = 0.972
Validation Accuracy = 0.752

EPOCH 13 ...
Training Accuracy = 0.976
Validation Accuracy = 0.754

EPOCH 14 ...
Training Accuracy = 0.972
Validation Accuracy = 0.741

EPOCH 15 ...
Training Accuracy = 0.977
Validation Accuracy = 0.761

EPOCH 16 ...
Training Accuracy = 0.982
Validation Accuracy = 0.751

EPOCH 17 ...
Training Accuracy = 0.977
Validation Accuracy = 0.744

EPOCH 18 ...
Training Accuracy = 0.979
Validation Accuracy = 0.755

EPOCH 19 ...
Training Accuracy = 0.984
Validation Accuracy = 0.760

EPOCH 20 ...
Training Accuracy = 0.976
Validation Accuracy = 0.753

EPOCH 21 ...
Training Accuracy = 0.987
Validation Accuracy = 0.774

EPOCH 22 ...
Training Accuracy = 0.988
Validation Accuracy = 0.762

EPOCH 23 ...
Training Accuracy = 0.989
Validation Accuracy = 0.764

EPOCH 24 ...
Training Accuracy = 0.987
Validation Accuracy = 0.765

EPOCH 25 ...
Training Accuracy = 0.986
Validation Accuracy = 0.763

EPOCH 26 ...
Training Accuracy = 0.985
Validation Accuracy = 0.765

EPOCH 27 ...
Training Accuracy = 0.987
Validation Accuracy = 0.765

EPOCH 28 ...
Training Accuracy = 0.986
Validation Accuracy = 0.748

EPOCH 29 ...
Training Accuracy = 0.996
Validation Accuracy = 0.780

EPOCH 30 ...
Training Accuracy = 0.987
Validation Accuracy = 0.749

EPOCH 31 ...
Training Accuracy = 0.984
Validation Accuracy = 0.767

EPOCH 32 ...
Training Accuracy = 0.986
Validation Accuracy = 0.758

EPOCH 33 ...
Training Accuracy = 0.995
Validation Accuracy = 0.788

EPOCH 34 ...
Training Accuracy = 0.986
Validation Accuracy = 0.767

EPOCH 35 ...
Training Accuracy = 0.990
Validation Accuracy = 0.783

EPOCH 36 ...
Training Accuracy = 0.976
Validation Accuracy = 0.747

EPOCH 37 ...
Training Accuracy = 0.989
Validation Accuracy = 0.780

EPOCH 38 ...
Training Accuracy = 0.990
Validation Accuracy = 0.778

EPOCH 39 ...
Training Accuracy = 0.995
Validation Accuracy = 0.792

EPOCH 40 ...
Training Accuracy = 0.992
Validation Accuracy = 0.760

EPOCH 41 ...
Training Accuracy = 0.991
Validation Accuracy = 0.781

EPOCH 42 ...
Training Accuracy = 0.985
Validation Accuracy = 0.759

EPOCH 43 ...
Training Accuracy = 0.996
Validation Accuracy = 0.774

EPOCH 44 ...
Training Accuracy = 0.990
Validation Accuracy = 0.772

EPOCH 45 ...
Training Accuracy = 0.989
Validation Accuracy = 0.761

EPOCH 46 ...
Training Accuracy = 0.990
Validation Accuracy = 0.767

EPOCH 47 ...
Training Accuracy = 0.990
Validation Accuracy = 0.778

EPOCH 48 ...
Training Accuracy = 0.988
Validation Accuracy = 0.785

EPOCH 49 ...
Training Accuracy = 0.995
Validation Accuracy = 0.792

EPOCH 50 ...
Training Accuracy = 0.996
Validation Accuracy = 0.784

EPOCH 51 ...
Training Accuracy = 0.990
Validation Accuracy = 0.780

EPOCH 52 ...
Training Accuracy = 0.993
Validation Accuracy = 0.782

EPOCH 53 ...
Training Accuracy = 0.992
Validation Accuracy = 0.770

EPOCH 54 ...
Training Accuracy = 0.995
Validation Accuracy = 0.774

EPOCH 55 ...
Training Accuracy = 0.988
Validation Accuracy = 0.776

EPOCH 56 ...
Training Accuracy = 0.996
Validation Accuracy = 0.783

EPOCH 57 ...
Training Accuracy = 0.996
Validation Accuracy = 0.779

EPOCH 58 ...
Training Accuracy = 0.997
Validation Accuracy = 0.778

EPOCH 59 ...
Training Accuracy = 0.994
Validation Accuracy = 0.777

EPOCH 60 ...
Training Accuracy = 0.994
Validation Accuracy = 0.775

EPOCH 61 ...
Training Accuracy = 0.998
Validation Accuracy = 0.796

EPOCH 62 ...
Training Accuracy = 0.993
Validation Accuracy = 0.780

EPOCH 63 ...
Training Accuracy = 0.998
Validation Accuracy = 0.788

EPOCH 64 ...
Training Accuracy = 0.973
Validation Accuracy = 0.748

EPOCH 65 ...
Training Accuracy = 0.989
Validation Accuracy = 0.772

EPOCH 66 ...
Training Accuracy = 0.994
Validation Accuracy = 0.778

EPOCH 67 ...
Training Accuracy = 0.995
Validation Accuracy = 0.782

EPOCH 68 ...
Training Accuracy = 0.996
Validation Accuracy = 0.798

EPOCH 69 ...
Training Accuracy = 0.996
Validation Accuracy = 0.790

EPOCH 70 ...
Training Accuracy = 0.996
Validation Accuracy = 0.790

EPOCH 71 ...
Training Accuracy = 0.997
Validation Accuracy = 0.802

EPOCH 72 ...
Training Accuracy = 0.988
Validation Accuracy = 0.763

EPOCH 73 ...
Training Accuracy = 0.995
Validation Accuracy = 0.795

EPOCH 74 ...
Training Accuracy = 0.997
Validation Accuracy = 0.790

EPOCH 75 ...
Training Accuracy = 0.999
Validation Accuracy = 0.800

EPOCH 76 ...
Training Accuracy = 0.996
Validation Accuracy = 0.782

EPOCH 77 ...
Training Accuracy = 0.988
Validation Accuracy = 0.772

EPOCH 78 ...
Training Accuracy = 0.996
Validation Accuracy = 0.775

EPOCH 79 ...
Training Accuracy = 0.997
Validation Accuracy = 0.775

EPOCH 80 ...
Training Accuracy = 0.994
Validation Accuracy = 0.788

EPOCH 81 ...
Training Accuracy = 0.997
Validation Accuracy = 0.782

EPOCH 82 ...
Training Accuracy = 0.990
Validation Accuracy = 0.772

EPOCH 83 ...
Training Accuracy = 0.994
Validation Accuracy = 0.788

EPOCH 84 ...
Training Accuracy = 0.996
Validation Accuracy = 0.775

EPOCH 85 ...
Training Accuracy = 0.997
Validation Accuracy = 0.790

EPOCH 86 ...
Training Accuracy = 0.996
Validation Accuracy = 0.782

EPOCH 87 ...
Training Accuracy = 0.996
Validation Accuracy = 0.792

EPOCH 88 ...
Training Accuracy = 0.992
Validation Accuracy = 0.783

EPOCH 89 ...
Training Accuracy = 0.997
Validation Accuracy = 0.804

EPOCH 90 ...
Training Accuracy = 0.996
Validation Accuracy = 0.785

EPOCH 91 ...
Training Accuracy = 0.996
Validation Accuracy = 0.790

EPOCH 92 ...
Training Accuracy = 0.995
Validation Accuracy = 0.783

EPOCH 93 ...
Training Accuracy = 0.994
Validation Accuracy = 0.799

EPOCH 94 ...
Training Accuracy = 0.998
Validation Accuracy = 0.795

EPOCH 95 ...
Training Accuracy = 0.992
Validation Accuracy = 0.788

EPOCH 96 ...
Training Accuracy = 0.992
Validation Accuracy = 0.782

EPOCH 97 ...
Training Accuracy = 0.998
Validation Accuracy = 0.804

EPOCH 98 ...
Training Accuracy = 0.998
Validation Accuracy = 0.793

EPOCH 99 ...
Training Accuracy = 0.996
Validation Accuracy = 0.785

EPOCH 100 ...
Training Accuracy = 0.997
Validation Accuracy = 0.777

Model saved

Second attemp with better preprocessing

In [ ]:
### Preprocess the data here.
###
### Step 1:
### According to the given paper, http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf
### We convert the data into YUV space using Y

import cv2

X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']


def RGB2YUV(image_data):
    yuv_image_data = []
    for i in range(len(image_data)):
        yuv_image_data.append(cv2.cvtColor(image_data[i], cv2.COLOR_RGB2YUV))
    return np.array(yuv_image_data)



X_train = RGB2YUV(X_train)
X_valid = RGB2YUV(X_valid)
X_test = RGB2YUV(X_test)
print('Features are now converted YUV!')
X_train.shape
In [40]:
f_mean = np.mean(X_train)
print(f_mean)
f_std = np.std(X_train)
print(f_std)

X_train = (X_train - f_mean) / f_std
X_valid = (X_valid - f_mean) / f_std
X_test = (X_test - f_mean) / f_std
81.91723852405062
66.13439739365434
In [41]:
X_train, y_train = shuffle(X_train, y_train)
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
rate = 0.001

logits = LeNet(x, input_channel=1, n_classes=n_classes)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

# Model evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
# **Traffic Sign Recognition** 



def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples


EPOCHS = 100
BATCH_SIZE = 128


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        training_accuracy = evaluate(X_train, y_train)    
        validation_accuracy = evaluate(X_valid, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Training Accuracy = {:.3f}".format(training_accuracy))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
     
    test_accuracy = evaluate(X_test, y_test)    
    print("Test Accuracy = {:.3f}".format(test_accuracy))
    print()
    saver.save(sess, './lenet')
    print("Model saved")
Training...

EPOCH 1 ...
Training Accuracy = 0.841
Validation Accuracy = 0.768

EPOCH 2 ...
Training Accuracy = 0.923
Validation Accuracy = 0.859

EPOCH 3 ...
Training Accuracy = 0.953
Validation Accuracy = 0.871

EPOCH 4 ...
Training Accuracy = 0.971
Validation Accuracy = 0.904

EPOCH 5 ...
Training Accuracy = 0.980
Validation Accuracy = 0.893

EPOCH 6 ...
Training Accuracy = 0.984
Validation Accuracy = 0.906

EPOCH 7 ...
Training Accuracy = 0.987
Validation Accuracy = 0.915

EPOCH 8 ...
Training Accuracy = 0.988
Validation Accuracy = 0.908

EPOCH 9 ...
Training Accuracy = 0.987
Validation Accuracy = 0.909

EPOCH 10 ...
Training Accuracy = 0.990
Validation Accuracy = 0.905

EPOCH 11 ...
Training Accuracy = 0.995
Validation Accuracy = 0.920

EPOCH 12 ...
Training Accuracy = 0.993
Validation Accuracy = 0.910

EPOCH 13 ...
Training Accuracy = 0.985
Validation Accuracy = 0.894

EPOCH 14 ...
Training Accuracy = 0.996
Validation Accuracy = 0.910

EPOCH 15 ...
Training Accuracy = 0.996
Validation Accuracy = 0.927

EPOCH 16 ...
Training Accuracy = 0.993
Validation Accuracy = 0.926

EPOCH 17 ...
Training Accuracy = 0.995
Validation Accuracy = 0.915

EPOCH 18 ...
Training Accuracy = 0.996
Validation Accuracy = 0.908

EPOCH 19 ...
Training Accuracy = 0.994
Validation Accuracy = 0.920

EPOCH 20 ...
Training Accuracy = 0.996
Validation Accuracy = 0.923

EPOCH 21 ...
Training Accuracy = 0.996
Validation Accuracy = 0.897

EPOCH 22 ...
Training Accuracy = 0.990
Validation Accuracy = 0.912

EPOCH 23 ...
Training Accuracy = 0.999
Validation Accuracy = 0.920

EPOCH 24 ...
Training Accuracy = 0.999
Validation Accuracy = 0.940

EPOCH 25 ...
Training Accuracy = 0.998
Validation Accuracy = 0.925

EPOCH 26 ...
Training Accuracy = 0.995
Validation Accuracy = 0.900

EPOCH 27 ...
Training Accuracy = 0.995
Validation Accuracy = 0.922

EPOCH 28 ...
Training Accuracy = 0.998
Validation Accuracy = 0.930

EPOCH 29 ...
Training Accuracy = 1.000
Validation Accuracy = 0.939

EPOCH 30 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 31 ...
Training Accuracy = 1.000
Validation Accuracy = 0.937

EPOCH 32 ...
Training Accuracy = 1.000
Validation Accuracy = 0.935

EPOCH 33 ...
Training Accuracy = 1.000
Validation Accuracy = 0.936

EPOCH 34 ...
Training Accuracy = 1.000
Validation Accuracy = 0.937

EPOCH 35 ...
Training Accuracy = 1.000
Validation Accuracy = 0.938

EPOCH 36 ...
Training Accuracy = 1.000
Validation Accuracy = 0.938

EPOCH 37 ...
Training Accuracy = 1.000
Validation Accuracy = 0.930

EPOCH 38 ...
Training Accuracy = 0.992
Validation Accuracy = 0.920

EPOCH 39 ...
Training Accuracy = 0.998
Validation Accuracy = 0.931

EPOCH 40 ...
Training Accuracy = 1.000
Validation Accuracy = 0.940

EPOCH 41 ...
Training Accuracy = 1.000
Validation Accuracy = 0.937

EPOCH 42 ...
Training Accuracy = 0.997
Validation Accuracy = 0.926

EPOCH 43 ...
Training Accuracy = 0.999
Validation Accuracy = 0.928

EPOCH 44 ...
Training Accuracy = 0.998
Validation Accuracy = 0.937

EPOCH 45 ...
Training Accuracy = 0.996
Validation Accuracy = 0.931

EPOCH 46 ...
Training Accuracy = 0.999
Validation Accuracy = 0.940

EPOCH 47 ...
Training Accuracy = 0.994
Validation Accuracy = 0.940

EPOCH 48 ...
Training Accuracy = 0.995
Validation Accuracy = 0.929

EPOCH 49 ...
Training Accuracy = 0.999
Validation Accuracy = 0.940

EPOCH 50 ...
Training Accuracy = 0.997
Validation Accuracy = 0.921

EPOCH 51 ...
Training Accuracy = 1.000
Validation Accuracy = 0.933

EPOCH 52 ...
Training Accuracy = 1.000
Validation Accuracy = 0.943

EPOCH 53 ...
Training Accuracy = 1.000
Validation Accuracy = 0.945

EPOCH 54 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 55 ...
Training Accuracy = 1.000
Validation Accuracy = 0.943

EPOCH 56 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 57 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 58 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 59 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 60 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 61 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 62 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 63 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 64 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 65 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 66 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 67 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 68 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 69 ...
Training Accuracy = 1.000
Validation Accuracy = 0.942

EPOCH 70 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 71 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 72 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 73 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 74 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 75 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 76 ...
Training Accuracy = 0.992
Validation Accuracy = 0.929

EPOCH 77 ...
Training Accuracy = 0.999
Validation Accuracy = 0.947

EPOCH 78 ...
Training Accuracy = 0.999
Validation Accuracy = 0.943

EPOCH 79 ...
Training Accuracy = 1.000
Validation Accuracy = 0.948

EPOCH 80 ...
Training Accuracy = 1.000
Validation Accuracy = 0.941

EPOCH 81 ...
Training Accuracy = 1.000
Validation Accuracy = 0.948

EPOCH 82 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 83 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 84 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 85 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 86 ...
Training Accuracy = 1.000
Validation Accuracy = 0.952

EPOCH 87 ...
Training Accuracy = 1.000
Validation Accuracy = 0.952

EPOCH 88 ...
Training Accuracy = 1.000
Validation Accuracy = 0.952

EPOCH 89 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 90 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 91 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 92 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 93 ...
Training Accuracy = 1.000
Validation Accuracy = 0.951

EPOCH 94 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 95 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 96 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

EPOCH 97 ...
Training Accuracy = 1.000
Validation Accuracy = 0.949

EPOCH 98 ...
Training Accuracy = 1.000
Validation Accuracy = 0.949

EPOCH 99 ...
Training Accuracy = 1.000
Validation Accuracy = 0.949

EPOCH 100 ...
Training Accuracy = 1.000
Validation Accuracy = 0.950

Test Accuracy = 0.933

Model saved
In [24]:
### We also plot bottom three least example images:
print("YUV example images:")
fg, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(10, 10))

ax1.imshow(train['features'][0])
ax1.set_title('RGB image')

ax2.imshow(yuv_image_data[:, :, 0], cmap='gray')
ax2.set_title('Y channel')

ax3.imshow(yuv_image_data[:, :, 1], cmap='gray')
ax3.set_title('U channel')

ax4.imshow(yuv_image_data[:, :, 2], cmap='gray')
ax4.set_title('V channel')

plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)

plt.show()
YUV example images:
In [1]:
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf

train_params_cifar = {
    'batch_size': 128,
    'n_epochs': 100,
    'initial_learning_rate': 0.01,
    'reduce_lr_epoch_1': 50,  # epochs * 0.5
    'reduce_lr_epoch_2': 75,  # epochs * 0.75
    'validation_set': True,
    'validation_split': None,  # None or float
    'shuffle': 'every_epoch',  # None, once_prior_train, every_epoch
    'normalization': 'by_chanels',  # None, divide_256, divide_255, by_chanels
    'use_Y': False,  # use only Y channel
    'data_augmentation': 0,  # [0, 1]
}
/home/stevenwudi/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
WARNING:tensorflow:From /home/stevenwudi/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Use the retry module or similar alternatives.
In [2]:
import json
# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
    model_params = json.load(fp)
In [3]:
# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
    print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
    print("\t%s: %s" % (k, v))
train_params['use_YUV'] = False
model_params['use_YUV'] = False
print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()
Params:
	train: True
	test: True
	model_type: DenseNet
	growth_rate: 12
	depth: 40
	dataset: GTSR
	total_blocks: 3
	keep_prob: 1.0
	weight_decay: 0.0001
	nesterov_momentum: 0.9
	reduction: 1.0
	should_save_logs: True
	should_save_model: True
	renew_logs: True
	bc_mode: False
Train params:
	batch_size: 128
	n_epochs: 100
	initial_learning_rate: 0.01
	reduce_lr_epoch_1: 50
	reduce_lr_epoch_2: 75
	validation_set: True
	validation_split: None
	shuffle: every_epoch
	normalization: by_chanels
	use_Y: False
	data_augmentation: 0
Prepare training data...
Initialize the model..
Build DenseNet model with 3 blocks, 12 composite layers each.
Reduction at transition layers: 1.0
WARNING:tensorflow:From /home/stevenwudi/PycharmProjects/Udacity/CarND-Traffic-Sign-Classifier-Project/models.py:417: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:

Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See tf.nn.softmax_cross_entropy_with_logits_v2.

Total training params: 1.1M
Loading trained model
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0/model.chkpt
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0/model.chkpt
Successfully load model from save path: saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0/model.chkpt
In [4]:
print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)
print("mean cross_entropy: %f, mean accuracy: %f" % (loss, accuracy))
total_prediction, y_test = model.predictions_test(data_provider.test, batch_size=100)
Data provider test images:  12630
Testing...
mean cross_entropy: 0.102550, mean accuracy: 0.974822
In [30]:
incorrectlist
Out[30]:
[{'correct': 8, 'index': 0, 'predicted': 5},
 {'correct': 25, 'index': 0, 'predicted': 0},
 {'correct': 25, 'index': 0, 'predicted': 30},
 {'correct': 30, 'index': 1, 'predicted': 31},
 {'correct': 8, 'index': 2, 'predicted': 3},
 {'correct': 12, 'index': 2, 'predicted': 41},
 {'correct': 38, 'index': 3, 'predicted': 40},
 {'correct': 22, 'index': 3, 'predicted': 25},
 {'correct': 29, 'index': 3, 'predicted': 18},
 {'correct': 39, 'index': 3, 'predicted': 33},
 {'correct': 26, 'index': 3, 'predicted': 18},
 {'correct': 1, 'index': 3, 'predicted': 4},
 {'correct': 12, 'index': 4, 'predicted': 38},
 {'correct': 4, 'index': 4, 'predicted': 2},
 {'correct': 30, 'index': 4, 'predicted': 31},
 {'correct': 40, 'index': 4, 'predicted': 36},
 {'correct': 4, 'index': 5, 'predicted': 2},
 {'correct': 29, 'index': 6, 'predicted': 25},
 {'correct': 18, 'index': 7, 'predicted': 26},
 {'correct': 17, 'index': 7, 'predicted': 38},
 {'correct': 12, 'index': 7, 'predicted': 38},
 {'correct': 39, 'index': 7, 'predicted': 33},
 {'correct': 2, 'index': 8, 'predicted': 1},
 {'correct': 26, 'index': 8, 'predicted': 8},
 {'correct': 39, 'index': 10, 'predicted': 33},
 {'correct': 21, 'index': 10, 'predicted': 18},
 {'correct': 23, 'index': 11, 'predicted': 31},
 {'correct': 39, 'index': 12, 'predicted': 33},
 {'correct': 8, 'index': 12, 'predicted': 5},
 {'correct': 18, 'index': 12, 'predicted': 21},
 {'correct': 25, 'index': 13, 'predicted': 28},
 {'correct': 8, 'index': 13, 'predicted': 5},
 {'correct': 3, 'index': 15, 'predicted': 5},
 {'correct': 28, 'index': 15, 'predicted': 21},
 {'correct': 21, 'index': 15, 'predicted': 12},
 {'correct': 17, 'index': 16, 'predicted': 7},
 {'correct': 39, 'index': 17, 'predicted': 33},
 {'correct': 21, 'index': 17, 'predicted': 1},
 {'correct': 17, 'index': 17, 'predicted': 7},
 {'correct': 5, 'index': 18, 'predicted': 1},
 {'correct': 39, 'index': 18, 'predicted': 33},
 {'correct': 21, 'index': 18, 'predicted': 1},
 {'correct': 17, 'index': 19, 'predicted': 7},
 {'correct': 8, 'index': 20, 'predicted': 5},
 {'correct': 4, 'index': 20, 'predicted': 1},
 {'correct': 18, 'index': 20, 'predicted': 26},
 {'correct': 25, 'index': 20, 'predicted': 0},
 {'correct': 29, 'index': 21, 'predicted': 18},
 {'correct': 26, 'index': 22, 'predicted': 18},
 {'correct': 8, 'index': 22, 'predicted': 3},
 {'correct': 42, 'index': 23, 'predicted': 12},
 {'correct': 18, 'index': 23, 'predicted': 21},
 {'correct': 21, 'index': 23, 'predicted': 1},
 {'correct': 25, 'index': 23, 'predicted': 0},
 {'correct': 25, 'index': 23, 'predicted': 12},
 {'correct': 35, 'index': 24, 'predicted': 37},
 {'correct': 17, 'index': 24, 'predicted': 38},
 {'correct': 2, 'index': 24, 'predicted': 1},
 {'correct': 39, 'index': 25, 'predicted': 33},
 {'correct': 25, 'index': 25, 'predicted': 0},
 {'correct': 17, 'index': 25, 'predicted': 7},
 {'correct': 4, 'index': 25, 'predicted': 2},
 {'correct': 2, 'index': 25, 'predicted': 5},
 {'correct': 12, 'index': 26, 'predicted': 38},
 {'correct': 35, 'index': 27, 'predicted': 36},
 {'correct': 25, 'index': 27, 'predicted': 0},
 {'correct': 24, 'index': 27, 'predicted': 29},
 {'correct': 39, 'index': 28, 'predicted': 33},
 {'correct': 17, 'index': 28, 'predicted': 7},
 {'correct': 39, 'index': 28, 'predicted': 33},
 {'correct': 39, 'index': 28, 'predicted': 33},
 {'correct': 7, 'index': 29, 'predicted': 8},
 {'correct': 8, 'index': 30, 'predicted': 5},
 {'correct': 39, 'index': 31, 'predicted': 33},
 {'correct': 24, 'index': 32, 'predicted': 18},
 {'correct': 39, 'index': 33, 'predicted': 33},
 {'correct': 23, 'index': 33, 'predicted': 31},
 {'correct': 22, 'index': 34, 'predicted': 23},
 {'correct': 5, 'index': 35, 'predicted': 7},
 {'correct': 8, 'index': 35, 'predicted': 10},
 {'correct': 17, 'index': 35, 'predicted': 7},
 {'correct': 8, 'index': 36, 'predicted': 5},
 {'correct': 40, 'index': 37, 'predicted': 12},
 {'correct': 26, 'index': 37, 'predicted': 18},
 {'correct': 38, 'index': 37, 'predicted': 7},
 {'correct': 18, 'index': 37, 'predicted': 21},
 {'correct': 12, 'index': 37, 'predicted': 13},
 {'correct': 28, 'index': 37, 'predicted': 30},
 {'correct': 18, 'index': 37, 'predicted': 21},
 {'correct': 18, 'index': 38, 'predicted': 21},
 {'correct': 17, 'index': 38, 'predicted': 12},
 {'correct': 5, 'index': 38, 'predicted': 1},
 {'correct': 22, 'index': 38, 'predicted': 23},
 {'correct': 8, 'index': 39, 'predicted': 5},
 {'correct': 18, 'index': 39, 'predicted': 21},
 {'correct': 17, 'index': 39, 'predicted': 38},
 {'correct': 35, 'index': 39, 'predicted': 37},
 {'correct': 8, 'index': 40, 'predicted': 5},
 {'correct': 29, 'index': 40, 'predicted': 18},
 {'correct': 41, 'index': 41, 'predicted': 42},
 {'correct': 17, 'index': 41, 'predicted': 5},
 {'correct': 39, 'index': 41, 'predicted': 33},
 {'correct': 21, 'index': 41, 'predicted': 1},
 {'correct': 21, 'index': 41, 'predicted': 1},
 {'correct': 13, 'index': 42, 'predicted': 32},
 {'correct': 26, 'index': 43, 'predicted': 18},
 {'correct': 0, 'index': 43, 'predicted': 1},
 {'correct': 21, 'index': 44, 'predicted': 18},
 {'correct': 27, 'index': 45, 'predicted': 11},
 {'correct': 8, 'index': 45, 'predicted': 5},
 {'correct': 3, 'index': 45, 'predicted': 5},
 {'correct': 11, 'index': 46, 'predicted': 13},
 {'correct': 26, 'index': 46, 'predicted': 18},
 {'correct': 37, 'index': 46, 'predicted': 35},
 {'correct': 40, 'index': 46, 'predicted': 35},
 {'correct': 25, 'index': 46, 'predicted': 30},
 {'correct': 32, 'index': 48, 'predicted': 13},
 {'correct': 4, 'index': 48, 'predicted': 3},
 {'correct': 22, 'index': 51, 'predicted': 23},
 {'correct': 18, 'index': 51, 'predicted': 21},
 {'correct': 18, 'index': 51, 'predicted': 21},
 {'correct': 17, 'index': 52, 'predicted': 38},
 {'correct': 25, 'index': 53, 'predicted': 0},
 {'correct': 17, 'index': 53, 'predicted': 38},
 {'correct': 40, 'index': 53, 'predicted': 36},
 {'correct': 18, 'index': 54, 'predicted': 21},
 {'correct': 28, 'index': 55, 'predicted': 29},
 {'correct': 6, 'index': 55, 'predicted': 20},
 {'correct': 39, 'index': 55, 'predicted': 33},
 {'correct': 26, 'index': 55, 'predicted': 18},
 {'correct': 8, 'index': 55, 'predicted': 5},
 {'correct': 17, 'index': 56, 'predicted': 38},
 {'correct': 21, 'index': 56, 'predicted': 18},
 {'correct': 8, 'index': 56, 'predicted': 5},
 {'correct': 29, 'index': 57, 'predicted': 25},
 {'correct': 0, 'index': 59, 'predicted': 8},
 {'correct': 5, 'index': 61, 'predicted': 1},
 {'correct': 3, 'index': 61, 'predicted': 5},
 {'correct': 26, 'index': 62, 'predicted': 18},
 {'correct': 4, 'index': 62, 'predicted': 1},
 {'correct': 29, 'index': 62, 'predicted': 25},
 {'correct': 4, 'index': 62, 'predicted': 2},
 {'correct': 6, 'index': 62, 'predicted': 20},
 {'correct': 5, 'index': 62, 'predicted': 1},
 {'correct': 41, 'index': 62, 'predicted': 42},
 {'correct': 8, 'index': 62, 'predicted': 10},
 {'correct': 26, 'index': 63, 'predicted': 18},
 {'correct': 8, 'index': 63, 'predicted': 5},
 {'correct': 31, 'index': 64, 'predicted': 20},
 {'correct': 17, 'index': 64, 'predicted': 38},
 {'correct': 22, 'index': 65, 'predicted': 23},
 {'correct': 26, 'index': 67, 'predicted': 18},
 {'correct': 18, 'index': 67, 'predicted': 21},
 {'correct': 39, 'index': 67, 'predicted': 33},
 {'correct': 17, 'index': 68, 'predicted': 38},
 {'correct': 0, 'index': 68, 'predicted': 8},
 {'correct': 39, 'index': 68, 'predicted': 33},
 {'correct': 17, 'index': 68, 'predicted': 38},
 {'correct': 3, 'index': 68, 'predicted': 5},
 {'correct': 18, 'index': 68, 'predicted': 21},
 {'correct': 22, 'index': 69, 'predicted': 23},
 {'correct': 24, 'index': 69, 'predicted': 18},
 {'correct': 17, 'index': 69, 'predicted': 38},
 {'correct': 0, 'index': 69, 'predicted': 1},
 {'correct': 22, 'index': 69, 'predicted': 25},
 {'correct': 31, 'index': 70, 'predicted': 20},
 {'correct': 27, 'index': 70, 'predicted': 11},
 {'correct': 42, 'index': 70, 'predicted': 12},
 {'correct': 24, 'index': 70, 'predicted': 18},
 {'correct': 8, 'index': 70, 'predicted': 5},
 {'correct': 26, 'index': 71, 'predicted': 8},
 {'correct': 31, 'index': 71, 'predicted': 20},
 {'correct': 8, 'index': 71, 'predicted': 5},
 {'correct': 22, 'index': 73, 'predicted': 23},
 {'correct': 8, 'index': 74, 'predicted': 5},
 {'correct': 25, 'index': 74, 'predicted': 0},
 {'correct': 3, 'index': 74, 'predicted': 5},
 {'correct': 3, 'index': 74, 'predicted': 2},
 {'correct': 21, 'index': 75, 'predicted': 22},
 {'correct': 31, 'index': 75, 'predicted': 20},
 {'correct': 17, 'index': 76, 'predicted': 38},
 {'correct': 11, 'index': 76, 'predicted': 31},
 {'correct': 17, 'index': 76, 'predicted': 38},
 {'correct': 1, 'index': 76, 'predicted': 4},
 {'correct': 40, 'index': 76, 'predicted': 37},
 {'correct': 18, 'index': 77, 'predicted': 21},
 {'correct': 8, 'index': 77, 'predicted': 5},
 {'correct': 39, 'index': 78, 'predicted': 33},
 {'correct': 22, 'index': 79, 'predicted': 23},
 {'correct': 35, 'index': 79, 'predicted': 37},
 {'correct': 42, 'index': 79, 'predicted': 12},
 {'correct': 8, 'index': 79, 'predicted': 5},
 {'correct': 23, 'index': 79, 'predicted': 31},
 {'correct': 26, 'index': 80, 'predicted': 4},
 {'correct': 38, 'index': 80, 'predicted': 40},
 {'correct': 35, 'index': 80, 'predicted': 37},
 {'correct': 3, 'index': 80, 'predicted': 5},
 {'correct': 29, 'index': 80, 'predicted': 25},
 {'correct': 22, 'index': 80, 'predicted': 23},
 {'correct': 25, 'index': 81, 'predicted': 0},
 {'correct': 25, 'index': 81, 'predicted': 0},
 {'correct': 26, 'index': 81, 'predicted': 18},
 {'correct': 17, 'index': 82, 'predicted': 38},
 {'correct': 35, 'index': 82, 'predicted': 37},
 {'correct': 8, 'index': 82, 'predicted': 5},
 {'correct': 31, 'index': 83, 'predicted': 20},
 {'correct': 39, 'index': 83, 'predicted': 33},
 {'correct': 21, 'index': 83, 'predicted': 18},
 {'correct': 2, 'index': 83, 'predicted': 1},
 {'correct': 31, 'index': 83, 'predicted': 20},
 {'correct': 2, 'index': 83, 'predicted': 5},
 {'correct': 39, 'index': 83, 'predicted': 33},
 {'correct': 27, 'index': 84, 'predicted': 11},
 {'correct': 15, 'index': 84, 'predicted': 1},
 {'correct': 21, 'index': 84, 'predicted': 1},
 {'correct': 39, 'index': 85, 'predicted': 33},
 {'correct': 35, 'index': 85, 'predicted': 37},
 {'correct': 26, 'index': 85, 'predicted': 4},
 {'correct': 18, 'index': 85, 'predicted': 21},
 {'correct': 30, 'index': 86, 'predicted': 5},
 {'correct': 2, 'index': 86, 'predicted': 1},
 {'correct': 26, 'index': 87, 'predicted': 4},
 {'correct': 17, 'index': 87, 'predicted': 7},
 {'correct': 25, 'index': 87, 'predicted': 0},
 {'correct': 39, 'index': 88, 'predicted': 33},
 {'correct': 39, 'index': 88, 'predicted': 33},
 {'correct': 22, 'index': 90, 'predicted': 23},
 {'correct': 1, 'index': 90, 'predicted': 4},
 {'correct': 18, 'index': 90, 'predicted': 10},
 {'correct': 38, 'index': 91, 'predicted': 40},
 {'correct': 39, 'index': 91, 'predicted': 33},
 {'correct': 21, 'index': 92, 'predicted': 18},
 {'correct': 1, 'index': 92, 'predicted': 4},
 {'correct': 21, 'index': 92, 'predicted': 12},
 {'correct': 42, 'index': 93, 'predicted': 12},
 {'correct': 23, 'index': 94, 'predicted': 31},
 {'correct': 29, 'index': 95, 'predicted': 24},
 {'correct': 18, 'index': 96, 'predicted': 26},
 {'correct': 22, 'index': 96, 'predicted': 25},
 {'correct': 2, 'index': 96, 'predicted': 1},
 {'correct': 4, 'index': 97, 'predicted': 1},
 {'correct': 21, 'index': 97, 'predicted': 1},
 {'correct': 21, 'index': 98, 'predicted': 1},
 {'correct': 2, 'index': 98, 'predicted': 1},
 {'correct': 39, 'index': 98, 'predicted': 36},
 {'correct': 7, 'index': 98, 'predicted': 8},
 {'correct': 17, 'index': 99, 'predicted': 38},
 {'correct': 8, 'index': 99, 'predicted': 5},
 {'correct': 31, 'index': 99, 'predicted': 20},
 {'correct': 6, 'index': 100, 'predicted': 42},
 {'correct': 21, 'index': 100, 'predicted': 18},
 {'correct': 8, 'index': 100, 'predicted': 3},
 {'correct': 39, 'index': 100, 'predicted': 33},
 {'correct': 11, 'index': 101, 'predicted': 30},
 {'correct': 21, 'index': 101, 'predicted': 29},
 {'correct': 22, 'index': 101, 'predicted': 25},
 {'correct': 26, 'index': 101, 'predicted': 1},
 {'correct': 21, 'index': 102, 'predicted': 1},
 {'correct': 26, 'index': 102, 'predicted': 18},
 {'correct': 17, 'index': 103, 'predicted': 38},
 {'correct': 21, 'index': 103, 'predicted': 1},
 {'correct': 17, 'index': 104, 'predicted': 12},
 {'correct': 18, 'index': 104, 'predicted': 21},
 {'correct': 35, 'index': 105, 'predicted': 33},
 {'correct': 4, 'index': 105, 'predicted': 1},
 {'correct': 4, 'index': 105, 'predicted': 12},
 {'correct': 39, 'index': 105, 'predicted': 33},
 {'correct': 22, 'index': 105, 'predicted': 25},
 {'correct': 21, 'index': 105, 'predicted': 29},
 {'correct': 31, 'index': 105, 'predicted': 20},
 {'correct': 25, 'index': 106, 'predicted': 0},
 {'correct': 4, 'index': 107, 'predicted': 1},
 {'correct': 6, 'index': 107, 'predicted': 42},
 {'correct': 39, 'index': 108, 'predicted': 33},
 {'correct': 39, 'index': 108, 'predicted': 33},
 {'correct': 27, 'index': 108, 'predicted': 23},
 {'correct': 17, 'index': 109, 'predicted': 38},
 {'correct': 17, 'index': 109, 'predicted': 12},
 {'correct': 17, 'index': 109, 'predicted': 7},
 {'correct': 18, 'index': 109, 'predicted': 21},
 {'correct': 18, 'index': 110, 'predicted': 21},
 {'correct': 17, 'index': 111, 'predicted': 38},
 {'correct': 21, 'index': 111, 'predicted': 18},
 {'correct': 26, 'index': 111, 'predicted': 18},
 {'correct': 8, 'index': 112, 'predicted': 3},
 {'correct': 8, 'index': 113, 'predicted': 5},
 {'correct': 12, 'index': 115, 'predicted': 13},
 {'correct': 26, 'index': 116, 'predicted': 4},
 {'correct': 0, 'index': 117, 'predicted': 4},
 {'correct': 17, 'index': 117, 'predicted': 38},
 {'correct': 12, 'index': 117, 'predicted': 13},
 {'correct': 21, 'index': 118, 'predicted': 29},
 {'correct': 25, 'index': 118, 'predicted': 0},
 {'correct': 26, 'index': 118, 'predicted': 8},
 {'correct': 21, 'index': 118, 'predicted': 1},
 {'correct': 23, 'index': 118, 'predicted': 31},
 {'correct': 22, 'index': 119, 'predicted': 11},
 {'correct': 23, 'index': 119, 'predicted': 31},
 {'correct': 22, 'index': 120, 'predicted': 25},
 {'correct': 22, 'index': 120, 'predicted': 23},
 {'correct': 26, 'index': 120, 'predicted': 4},
 {'correct': 21, 'index': 120, 'predicted': 18},
 {'correct': 39, 'index': 120, 'predicted': 33},
 {'correct': 21, 'index': 121, 'predicted': 1},
 {'correct': 8, 'index': 121, 'predicted': 5},
 {'correct': 4, 'index': 121, 'predicted': 1},
 {'correct': 2, 'index': 121, 'predicted': 1},
 {'correct': 21, 'index': 122, 'predicted': 1},
 {'correct': 28, 'index': 122, 'predicted': 29},
 {'correct': 39, 'index': 122, 'predicted': 33},
 {'correct': 22, 'index': 123, 'predicted': 11},
 {'correct': 26, 'index': 123, 'predicted': 4},
 {'correct': 8, 'index': 123, 'predicted': 5},
 {'correct': 28, 'index': 123, 'predicted': 24},
 {'correct': 3, 'index': 123, 'predicted': 16},
 {'correct': 21, 'index': 124, 'predicted': 18},
 {'correct': 25, 'index': 125, 'predicted': 0}]
In [31]:
import numpy as np

incorrectlist = []
for i in range(len(total_prediction)):
    #if not correctness(y_test[i],total_prediction[i]):
    for j in range(len(y_test[i])):
        if not np.argmax(y_test[i][j]) == np.argmax(total_prediction[i][j]):
            correct_classId = np.argmax(y_test[i][j])
            predict_classId = np.argmax(total_prediction[i][j])
            incorrectlist.append({'index':i*100+j, 'correct':correct_classId, 'predicted':predict_classId})
In [32]:
import pandas as pd
incorrectmatrix = {}
modeCount = 0
# get the label description from the CSV file.
classLabelList = pd.read_csv('signnames.csv')
for i in range(len(incorrectlist)):
    predicted = incorrectlist[i]['predicted']
    correct = incorrectlist[i]['correct']
    index = incorrectlist[i]['index']
    bucket = str(correct)+"+"+str(predicted)
    incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples':[]})
                                                     
    # add to the count
    count = incorrectinstance['count'] + 1
    
    # add to samples of this correct to predicted condition
    samples = incorrectinstance['samples']
    samples.append(index)
    
    # put back in the list
    incorrectmatrix[bucket] = {'count': count, 'correct':correct, 'predicted':predicted, 'samples':samples}
    
    # update most common error
    if count > modeCount:
        modeCount = count
        modeBucket = bucket
    
# get the list of buckets and sort them
def compare_bucket_count(bucket):
    return modeCount-incorrectmatrix[bucket]['count']

sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)

# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)

# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)

print("\nTop Twenty Distribution of buckets with incorrect predicted test dataset labels:")
for n in range(20):
    bucket = sortedBuckets[n]
    cclassId = incorrectmatrix[bucket]['correct']
    pclassId = incorrectmatrix[bucket]['predicted']
    count = incorrectmatrix[bucket]['count']
    cdescription = classLabelList[classLabelList.ClassId==cclassId].SignName.to_string(header=False,index=False)
    pdescription = classLabelList[classLabelList.ClassId==pclassId].SignName.to_string(header=False,index=False)
    print("incorrect set count: {0:4d}  CClassId: {1:02d} Description: {2}\n                           PClassId: {3:02d} Description: {4}".format(count, cclassId, cdescription, pclassId, pdescription))
Number of unique buckets in incorrect set:  82 

Mode Bucket:  39+33 with count:  29

Top Twenty Distribution of buckets with incorrect predicted test dataset labels:
incorrect set count:   29  CClassId: 39 Description: Keep left
                           PClassId: 33 Description: Turn right ahead
incorrect set count:   22  CClassId: 08 Description: Speed limit (120km/h)
                           PClassId: 05 Description: Speed limit (80km/h)
incorrect set count:   18  CClassId: 17 Description: No entry
                           PClassId: 38 Description: Keep right
incorrect set count:   16  CClassId: 18 Description: General caution
                           PClassId: 21 Description: Double curve
incorrect set count:   13  CClassId: 25 Description: Road work
                           PClassId: 00 Description: Speed limit (20km/h)
incorrect set count:   13  CClassId: 21 Description: Double curve
                           PClassId: 01 Description: Speed limit (30km/h)
incorrect set count:   12  CClassId: 26 Description: Traffic signals
                           PClassId: 18 Description: General caution
incorrect set count:   10  CClassId: 22 Description: Bumpy road
                           PClassId: 23 Description: Slippery road
incorrect set count:    9  CClassId: 21 Description: Double curve
                           PClassId: 18 Description: General caution
incorrect set count:    8  CClassId: 17 Description: No entry
                           PClassId: 07 Description: Speed limit (100km/h)
incorrect set count:    8  CClassId: 31 Description: Wild animals crossing
                           PClassId: 20 Description: Dangerous curve to the right
incorrect set count:    7  CClassId: 02 Description: Speed limit (50km/h)
                           PClassId: 01 Description: Speed limit (30km/h)
incorrect set count:    6  CClassId: 22 Description: Bumpy road
                           PClassId: 25 Description: Road work
incorrect set count:    6  CClassId: 23 Description: Slippery road
                           PClassId: 31 Description: Wild animals crossing
incorrect set count:    6  CClassId: 03 Description: Speed limit (60km/h)
                           PClassId: 05 Description: Speed limit (80km/h)
incorrect set count:    6  CClassId: 04 Description: Speed limit (70km/h)
                           PClassId: 01 Description: Speed limit (30km/h)
incorrect set count:    6  CClassId: 35 Description: Ahead only
                           PClassId: 37 Description: Go straight or left
incorrect set count:    6  CClassId: 26 Description: Traffic signals
                           PClassId: 04 Description: Speed limit (70km/h)
incorrect set count:    4  CClassId: 08 Description: Speed limit (120km/h)
                           PClassId: 03 Description: Speed limit (60km/h)
incorrect set count:    4  CClassId: 01 Description: Speed limit (30km/h)
                           PClassId: 04 Description: Speed limit (70km/h)
In [63]:
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
from tqdm import tqdm
import random
import time
from matplotlib import gridspec

def draw_sample_incorrectmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
    n_samples = 11
    n_labels = 10
    
    # size of each sample
    fig = plt.figure(figsize=(n_samples*1.8, n_labels))
    w_ratios = [1 for n in range(n_samples)]
    w_ratios[:0] = [int(n_samples*0.8)]
    h_ratios = [1 for n in range(n_labels)]

    # gridspec
    time.sleep(1) # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_samples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
    labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
    for a in labelset_pbar:
        cclassId = incorrectmatrix[sortedBuckets[n_labels-a-1]]['correct']
        pclassId = incorrectmatrix[sortedBuckets[n_labels-a-1]]['predicted']
        cdescription = classLabelList[classLabelList.ClassId==cclassId].SignName.to_string(header=False,index=False)
        pdescription = classLabelList[classLabelList.ClassId==pclassId].SignName.to_string(header=False,index=False)
        count = incorrectmatrix[sortedBuckets[n_labels-a-1]]['count']
        for b in range(n_samples):
            i = a*(n_samples+1) + b
            ax = plt.Subplot(fig, grid[i])
            if b == 0:
                ax.annotate('CClassId %d (%d): %s\nPClassId %d: %s'%(cclassId, count, cdescription, pclassId, pdescription), xy=(0,0), xytext=(0.0,0.3))
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
            else:
                random_i = random.choice(incorrectmatrix[sortedBuckets[n_labels-a-1]]['samples'])
                image = dataset[random_i]
                if cmap == None:
                    ax.imshow(image)
                else:
                    # yuv = cv2.split(image)
                    # ax.imshow(yuv[0], cmap=cmap)
                    ax.imshow(image, cmap=cmap)
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
                
        # We also plot the GT image on the right
        i = a*(n_samples+1) + n_samples
        ax = plt.Subplot(fig, grid[i])
        
        img_idx = np.where(y_train==pclassId)
        random_i = random.choice(img_idx[0])
        image =X_train[random_i]
        if cmap == None:
            ax.imshow(image)
        else:
            ax.imshow(image, cmap=cmap)
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)
    
        # hide the borders\
        if a == (n_labels-1):
            all_axes = fig.get_axes()
            for ax in all_axes:
                for sp in ax.spines.values():
                    sp.set_visible(False)

    plt.show()

draw_sample_incorrectmatrix('Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set', sortedBuckets, incorrectmatrix, test['features'])
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:   0%|          | 0/10 [00:00<?, ?labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  10%|â–ˆ         | 1/10 [00:00<00:05,  1.66labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  20%|██        | 2/10 [00:00<00:03,  2.21labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  30%|███       | 3/10 [00:01<00:02,  2.50labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  40%|████      | 4/10 [00:01<00:02,  2.66labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  50%|█████     | 5/10 [00:01<00:01,  2.78labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  60%|██████    | 6/10 [00:02<00:01,  2.84labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  70%|███████   | 7/10 [00:02<00:01,  2.90labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  80%|████████  | 8/10 [00:02<00:00,  2.94labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set:  90%|█████████ | 9/10 [00:03<00:00,  2.96labels/s]
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set: 100%|██████████| 10/10 [00:03<00:00,  2.96labels/s]
In [1]:
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf
import numpy as np
import json
import pandas as pd
from tqdm import tqdm
import random
import time
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
% matplotlib inline
from matplotlib import gridspec

# Load pickled data
import pickle
training_file = './data/train.p'
validation_file = './data/valid.p'
testing_file = './data/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)

X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']


train_params_cifar = {
    'batch_size': 64,
    'n_epochs': 500,
    'initial_learning_rate': 0.05,
    'reduce_lr_epoch_1': 50,  # epochs * 0.5
    'reduce_lr_epoch_2': 75,  # epochs * 0.75
    'validation_set': True,
    'validation_split': None,  # None or float
    'shuffle': 'every_epoch',  # None, once_prior_train, every_epoch
    'normalization': 'by_chanels',  # None, divide_256, divide_255, by_chanels
    'use_YUV': True,
    'use_Y': False,  # use only Y channel
    'data_augmentation': 0,  # [0, 1]
}


# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
    model_params = json.load(fp)

# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
    print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
    print("\t%s: %s" % (k, v))


print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()

print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)
print("mean cross_entropy: %f, mean accuracy: %f" % (loss, accuracy))
total_prediction, y_test = model.predictions_test(data_provider.test, batch_size=100)


# Plotting incorrect examples
incorrectlist = []
for i in range(len(total_prediction)):
    #if not correctness(y_test[i],total_prediction[i]):
    for j in range(len(y_test[i])):
        if not np.argmax(y_test[i][j]) == np.argmax(total_prediction[i][j]):
            correct_classId = np.argmax(y_test[i][j])
            predict_classId = np.argmax(total_prediction[i][j])
            incorrectlist.append({'index':i*100+j, 'correct':correct_classId, 'predicted':predict_classId})


incorrectmatrix = {}
modeCount = 0
# get the label description from the CSV file.
classLabelList = pd.read_csv('signnames.csv')
for i in range(len(incorrectlist)):
    predicted = incorrectlist[i]['predicted']
    correct = incorrectlist[i]['correct']
    index = incorrectlist[i]['index']
    bucket = str(correct) + "+" + str(predicted)
    incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples': []})

    # add to the count
    count = incorrectinstance['count'] + 1

    # add to samples of this correct to predicted condition
    samples = incorrectinstance['samples']
    samples.append(index)

    # put back in the list
    incorrectmatrix[bucket] = {'count': count, 'correct': correct, 'predicted': predicted, 'samples': samples}

    # update most common error
    if count > modeCount:
        modeCount = count
        modeBucket = bucket


# get the list of buckets and sort them
def compare_bucket_count(bucket):
    return modeCount - incorrectmatrix[bucket]['count']


sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)

# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)

# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)

print("\nTop Twenty Distribution of buckets with incorrect predicted test dataset labels:")
for n in range(20):
    bucket = sortedBuckets[n]
    cclassId = incorrectmatrix[bucket]['correct']
    pclassId = incorrectmatrix[bucket]['predicted']
    count = incorrectmatrix[bucket]['count']
    cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
    pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
    print(
        "incorrect set count: {0:4d}  CClassId: {1:02d} Description: {2}\n                           PClassId: {3:02d} Description: {4}".format(
            count, cclassId, cdescription, pclassId, pdescription))


def draw_sample_incorrectmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
    n_samples = 11
    n_labels = 10

    # size of each sample
    fig = plt.figure(figsize=(n_samples * 1.8, n_labels))
    w_ratios = [1 for n in range(n_samples)]
    w_ratios[:0] = [int(n_samples * 0.8)]
    h_ratios = [1 for n in range(n_labels)]

    # gridspec
    time.sleep(1)  # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_samples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
                             height_ratios=h_ratios)
    labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
    for a in labelset_pbar:
        cclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['correct']
        pclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['predicted']
        cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
        pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
        count = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['count']
        for b in range(n_samples):
            i = a * (n_samples + 1) + b
            ax = plt.Subplot(fig, grid[i])
            if b == 0:
                ax.annotate(
                    'CClassId %d (%d): %s\nPClassId %d: %s' % (cclassId, count, cdescription, pclassId, pdescription),
                    xy=(0, 0), xytext=(0.0, 0.3))
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
            else:
                random_i = random.choice(incorrectmatrix[sortedBuckets[n_labels - a - 1]]['samples'])
                image = dataset[random_i]
                if cmap == None:
                    ax.imshow(image)
                else:
                    # yuv = cv2.split(image)
                    # ax.imshow(yuv[0], cmap=cmap)
                    ax.imshow(image, cmap=cmap)
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)

        # We also plot the GT image on the right
        i = a * (n_samples + 1) + n_samples
        ax = plt.Subplot(fig, grid[i])

        img_idx = np.where(y_train == pclassId)
        random_i = random.choice(img_idx[0])
        image = X_train[random_i]
        if cmap == None:
            ax.imshow(image)
        else:
            ax.imshow(image, cmap=cmap)
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)

        # hide the borders\
        if a == (n_labels - 1):
            all_axes = fig.get_axes()
            for ax in all_axes:
                for sp in ax.spines.values():
                    sp.set_visible(False)

    plt.show()

draw_sample_incorrectmatrix(
    'Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set',
    sortedBuckets, incorrectmatrix, test['features'])
/home/stevenwudi/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
WARNING:tensorflow:From /home/stevenwudi/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Use the retry module or similar alternatives.
Params:
	train: True
	test: True
	model_type: DenseNet
	growth_rate: 12
	depth: 40
	dataset: GTSR
	total_blocks: 3
	keep_prob: 1.0
	weight_decay: 0.0001
	nesterov_momentum: 0.9
	reduction: 1.0
	should_save_logs: True
	should_save_model: True
	renew_logs: True
	bc_mode: False
Train params:
	batch_size: 64
	n_epochs: 500
	initial_learning_rate: 0.05
	reduce_lr_epoch_1: 50
	reduce_lr_epoch_2: 75
	validation_set: True
	validation_split: None
	shuffle: every_epoch
	normalization: by_chanels
	use_YUV: True
	use_Y: False
	data_augmentation: 0
Prepare training data...
Initialize the model..
Build DenseNet model with 3 blocks, 12 composite layers each.
Reduction at transition layers: 1.0
WARNING:tensorflow:From /home/stevenwudi/PycharmProjects/Udacity/CarND-Traffic-Sign-Classifier-Project/models.py:425: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:

Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See tf.nn.softmax_cross_entropy_with_logits_v2.

Total training params: 1.1M
Loading trained model
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
Successfully load model from save path: saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
Data provider test images:  12630
Testing...
mean cross_entropy: 0.069493, mean accuracy: 0.987728

Number of unique buckets in incorrect set:  35 

Mode Bucket:  27+28 with count:  30

Top Twenty Distribution of buckets with incorrect predicted test dataset labels:
incorrect set count:   30  CClassId: 08 Description: Speed limit (120km/h)
                           PClassId: 05 Description: Speed limit (80km/h)
incorrect set count:   30  CClassId: 22 Description: Bumpy road
                           PClassId: 25 Description: Road work
incorrect set count:   30  CClassId: 27 Description: Pedestrians
                           PClassId: 28 Description: Children crossing
incorrect set count:    7  CClassId: 09 Description: No passing
                           PClassId: 03 Description: Speed limit (60km/h)
incorrect set count:    7  CClassId: 18 Description: General caution
                           PClassId: 27 Description: Pedestrians
incorrect set count:    5  CClassId: 03 Description: Speed limit (60km/h)
                           PClassId: 05 Description: Speed limit (80km/h)
incorrect set count:    4  CClassId: 06 Description: End of speed limit (80km/h)
                           PClassId: 42 Description: End of no passing by vehicles over 3.5 metric ...
incorrect set count:    4  CClassId: 18 Description: General caution
                           PClassId: 26 Description: Traffic signals
incorrect set count:    3  CClassId: 12 Description: Priority road
                           PClassId: 13 Description: Yield
incorrect set count:    3  CClassId: 02 Description: Speed limit (50km/h)
                           PClassId: 01 Description: Speed limit (30km/h)
incorrect set count:    3  CClassId: 38 Description: Keep right
                           PClassId: 13 Description: Yield
incorrect set count:    2  CClassId: 38 Description: Keep right
                           PClassId: 40 Description: Roundabout mandatory
incorrect set count:    2  CClassId: 12 Description: Priority road
                           PClassId: 15 Description: No vehicles
incorrect set count:    2  CClassId: 06 Description: End of speed limit (80km/h)
                           PClassId: 40 Description: Roundabout mandatory
incorrect set count:    2  CClassId: 06 Description: End of speed limit (80km/h)
                           PClassId: 41 Description: End of no passing
incorrect set count:    2  CClassId: 21 Description: Double curve
                           PClassId: 02 Description: Speed limit (50km/h)
incorrect set count:    1  CClassId: 25 Description: Road work
                           PClassId: 40 Description: Roundabout mandatory
incorrect set count:    1  CClassId: 30 Description: Beware of ice/snow
                           PClassId: 11 Description: Right-of-way at the next intersection
incorrect set count:    1  CClassId: 25 Description: Road work
                           PClassId: 11 Description: Right-of-way at the next intersection
incorrect set count:    1  CClassId: 12 Description: Priority road
                           PClassId: 35 Description: Ahead only
Test set 10 ten incorrect sample images  using RGB as input, right most is the predicted image in the training set: 100%|██████████| 10/10 [00:02<00:00,  3.49labels/s]

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [2]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import cv2 

def labels_to_one_hot(labels, n_classes=43+1):
    """Convert 1D array of labels to one hot representation

    Args:
        labels: 1D numpy array
    """
    new_labels = np.zeros((n_classes,))
    new_labels[labels] = 1
    return new_labels
    
    
def draw_sample_newimage_labels(datasettxt, labeldata, dataset, cmap=None):
    n_maxsamples = 8
    n_labels = len(labeldata)
    
    # size of each sample
    fig = plt.figure(figsize=(n_maxsamples*1.8, n_labels))
    w_ratios = [1 for n in range(n_maxsamples)]
    w_ratios[:0] = [int(n_maxsamples*0.8)]
    h_ratios = [1 for n in range(n_labels)]

    # gridspec
    time.sleep(1) # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_maxsamples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
    labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
    for a in labelset_pbar:
        classId = labeldata[a]['label']
        description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
        count = labeldata[a]['count']
        for b in range(n_maxsamples+1):
            i = a*(n_maxsamples+1) + b
            ax = plt.Subplot(fig, grid[i])
            if b == 0:
                ax.annotate('ClassId %d (%d): %s'%(classId, count, description), xy=(0,0), xytext=(0.0,0.5))
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
            else:
                if (b-1) < len(labeldata[a]['samples']):
                    image_rgb = dataset[labeldata[a]['samples'][b-1]]
                    image = image_rgb.copy()
                    image[:,:,0] = image_rgb[:,:,2]
                    image[:,:,2] = image_rgb[:,:,0]

                    if cmap == None:
                        ax.imshow(image)
                    else:
                        # yuv = cv2.split(image)
                        # ax.imshow(yuv[0], cmap=cmap)
                        ax.imshow(image, cmap=cmap)
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
    
        # hide the borders\
        if a == (n_labels-1):
            all_axes = fig.get_axes()
            for ax in all_axes:
                for sp in ax.spines.values():
                    sp.set_visible(False)

    plt.show()

newimages = []
newlabels = []
new_onehot = []
newlabelsdata = []
directories = "./newimages"
subdirs = os.listdir(directories)
for subdir in subdirs:
    classId = int(subdir.split("-")[0])
    classinfo = {'label':classId,'count':0, 'samples':[]}
    filepath = directories+"/"+subdir
    for filename in os.listdir(filepath):
        image_filepath = filepath+"/"+filename
        image = cv2.imread(image_filepath)
        image = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
        newimages.append(image)
        newlabels.append(classId)
        new_onehot.append(labels_to_one_hot(classId))
        classinfo['count'] += 1
        classinfo['samples'].append(len(newimages)-1)
    if classinfo['count'] > 0:
        print("appending: ", classinfo)
        newlabelsdata.append(classinfo)

newimages = np.array(newimages)
newlabels = np.array(newlabels)
new_onehot = np.array(new_onehot)

draw_sample_newimage_labels("New samples (RGB)", newlabelsdata, newimages)

print("done")
appending:  {'label': 14, 'count': 3, 'samples': [0, 1, 2]}
appending:  {'label': 43, 'count': 6, 'samples': [3, 4, 5, 6, 7, 8]}
appending:  {'label': 38, 'count': 1, 'samples': [9]}
appending:  {'label': 28, 'count': 1, 'samples': [10]}
appending:  {'label': 29, 'count': 1, 'samples': [11]}
appending:  {'label': 27, 'count': 2, 'samples': [12, 13]}
appending:  {'label': 22, 'count': 1, 'samples': [14]}
appending:  {'label': 26, 'count': 1, 'samples': [15]}
appending:  {'label': 25, 'count': 1, 'samples': [16]}
appending:  {'label': 17, 'count': 2, 'samples': [17, 18]}
appending:  {'label': 18, 'count': 1, 'samples': [19]}
New samples (RGB): 100%|██████████| 11/11 [00:02<00:00,  4.31labels/s]
done

Predict the Sign Type for Each Image

In [5]:
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf
import numpy as np
import json
import pandas as pd
from tqdm import tqdm
import random
import time
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
% matplotlib inline
from matplotlib import gridspec

# Load pickled data
import pickle
training_file = './data/train.p'
validation_file = './data/valid.p'
testing_file = './data/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)

X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']


train_params_cifar = {
    'batch_size': 64,
    'n_epochs': 500,
    'initial_learning_rate': 0.05,
    'reduce_lr_epoch_1': 50,  # epochs * 0.5
    'reduce_lr_epoch_2': 75,  # epochs * 0.75
    'validation_set': True,
    'validation_split': None,  # None or float
    'shuffle': 'every_epoch',  # None, once_prior_train, every_epoch
    'normalization': 'by_chanels',  # None, divide_256, divide_255, by_chanels
    'use_YUV': True,
    'use_Y': False,  # use only Y channel
    'data_augmentation': 0,  # [0, 1]
}


# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
    model_params = json.load(fp)

# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
    print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
    print("\t%s: %s" % (k, v))


model_params['use_Y'] = False
print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()

print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)

import cv2
def labels_to_one_hot(labels, n_classes=43+1):
    """Convert 1D array of labels to one hot representation

    Args:
        labels: 1D numpy array
    """
    new_labels = np.zeros((n_classes,))
    new_labels[labels] = 1
    return new_labels
newimages = []
newlabels = []
new_onehot = []
newlabelsdata = []
directories = "./newimages"
subdirs = os.listdir(directories)
for subdir in subdirs:
    classId = int(subdir.split("-")[0])
    classinfo = {'label':classId,'count':0, 'samples':[]}
    filepath = directories+"/"+subdir
    for filename in os.listdir(filepath):
        image_filepath = filepath+"/"+filename
        image = cv2.imread(image_filepath)
        image_rgb = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
        image = image_rgb.copy()
        image[:, :, 0] = image_rgb[:, :, 2]
        image[:, :, 2] = image_rgb[:, :, 0]
        newimages.append(image)
        newlabels.append(classId)
        new_onehot.append(labels_to_one_hot(classId))
        classinfo['count'] += 1
        classinfo['samples'].append(len(newimages)-1)
    if classinfo['count'] > 0:
        print("appending: ", classinfo)
        newlabelsdata.append(classinfo)

newimages = np.array(newimages)
newlabels = np.array(newlabels)
new_onehot = np.array(new_onehot)

from data_providers.GermanTrafficSign import RGB2YUV

X_test_new = RGB2YUV(newimages)
new_image = np.zeros(X_test_new.shape)

for i in range(X_test_new.shape[-1]):
    new_image[:, :, :, i] = ((X_test_new[:, :, :, i] - data_provider._means[i]) /data_provider._stds[i])


y_new_onehot = model.predictions_one_image(new_image)[0]
predict_classId = np.argmax(y_new_onehot, axis=1)



incorrectlist = []
for i in range(len(y_new_onehot)):
    correct_classId = np.argmax(new_onehot[i],0)
    predict_classId = np.argmax(y_new_onehot[i],0)
    incorrectlist.append({'index':i, 'correct':correct_classId, 'predicted':predict_classId})


incorrectmatrix = {}
modeCount = 0
for i in range(len(incorrectlist)):
    predicted = incorrectlist[i]['predicted']
    correct = incorrectlist[i]['correct']
    index = incorrectlist[i]['index']
    bucket = str(correct) + "+" + str(predicted)
    incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples': []})

    # add to the count
    count = incorrectinstance['count'] + 1

    # add to samples of this correct to predicted condition
    samples = incorrectinstance['samples']
    samples.append(index)

    # put back in the list
    incorrectmatrix[bucket] = {'count': count, 'correct': correct, 'predicted': predicted, 'samples': samples}

    # update most common error
    if count > modeCount:
        modeCount = count
        modeBucket = bucket


# get the list of buckets and sort them
def compare_bucket_count(bucket):
    return modeCount - incorrectmatrix[bucket]['count']


sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)

# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)

# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)
classLabelList = pd.read_csv('signnames.csv')
print("\nDistribution of buckets with predicted test dataset labels:")
for n in range(len(sortedBuckets)):
    bucket = sortedBuckets[n]
    cclassId = incorrectmatrix[bucket]['correct']
    pclassId = incorrectmatrix[bucket]['predicted']
    count = incorrectmatrix[bucket]['count']
    cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
    pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
    print(
        "incorrect set count: {0:4d}  CClassId: {1:02d} Description: {2}\n                           PClassId: {3:02d} Description: {4}".format(
            count, cclassId, cdescription, pclassId, pdescription))
Params:
	train: True
	test: True
	model_type: DenseNet
	growth_rate: 12
	depth: 40
	dataset: GTSR
	total_blocks: 3
	keep_prob: 1.0
	weight_decay: 0.0001
	nesterov_momentum: 0.9
	reduction: 1.0
	should_save_logs: True
	should_save_model: True
	renew_logs: True
	bc_mode: False
Train params:
	batch_size: 64
	n_epochs: 500
	initial_learning_rate: 0.05
	reduce_lr_epoch_1: 50
	reduce_lr_epoch_2: 75
	validation_set: True
	validation_split: None
	shuffle: every_epoch
	normalization: by_chanels
	use_YUV: True
	use_Y: False
	data_augmentation: 0
Prepare training data...
Initialize the model..
Build DenseNet model with 3 blocks, 12 composite layers each.
Reduction at transition layers: 1.0
Total training params: 1.1M
Loading trained model
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
INFO:tensorflow:Restoring parameters from saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
Successfully load model from save path: saves/DenseNet_growth_rate=12_depth=40_dataset_GTSR_augmented_0_use_YUV_True/model.chkpt
Data provider test images:  12630
Testing...
appending:  {'label': 14, 'count': 3, 'samples': [0, 1, 2]}
appending:  {'label': 43, 'count': 6, 'samples': [3, 4, 5, 6, 7, 8]}
appending:  {'label': 38, 'count': 1, 'samples': [9]}
appending:  {'label': 28, 'count': 1, 'samples': [10]}
appending:  {'label': 29, 'count': 1, 'samples': [11]}
appending:  {'label': 27, 'count': 2, 'samples': [12, 13]}
appending:  {'label': 22, 'count': 1, 'samples': [14]}
appending:  {'label': 26, 'count': 1, 'samples': [15]}
appending:  {'label': 25, 'count': 1, 'samples': [16]}
appending:  {'label': 17, 'count': 2, 'samples': [17, 18]}
appending:  {'label': 18, 'count': 1, 'samples': [19]}

Number of unique buckets in incorrect set:  17 

Mode Bucket:  14+14 with count:  2

Distribution of buckets with predicted test dataset labels:
incorrect set count:    2  CClassId: 14 Description: Stop
                           PClassId: 14 Description: Stop
incorrect set count:    2  CClassId: 27 Description: Pedestrians
                           PClassId: 13 Description: Yield
incorrect set count:    2  CClassId: 17 Description: No entry
                           PClassId: 17 Description: No entry
incorrect set count:    1  CClassId: 14 Description: Stop
                           PClassId: 17 Description: No entry
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 14 Description: Stop
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 40 Description: Roundabout mandatory
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 18 Description: General caution
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 30 Description: Beware of ice/snow
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 33 Description: Turn right ahead
incorrect set count:    1  CClassId: 43 Description: Series([], )
                           PClassId: 34 Description: Turn left ahead
incorrect set count:    1  CClassId: 38 Description: Keep right
                           PClassId: 13 Description: Yield
incorrect set count:    1  CClassId: 28 Description: Children crossing
                           PClassId: 28 Description: Children crossing
incorrect set count:    1  CClassId: 29 Description: Bicycles crossing
                           PClassId: 29 Description: Bicycles crossing
incorrect set count:    1  CClassId: 22 Description: Bumpy road
                           PClassId: 13 Description: Yield
incorrect set count:    1  CClassId: 26 Description: Traffic signals
                           PClassId: 26 Description: Traffic signals
incorrect set count:    1  CClassId: 25 Description: Road work
                           PClassId: 25 Description: Road work
incorrect set count:    1  CClassId: 18 Description: General caution
                           PClassId: 18 Description: General caution
In [92]:
def draw_sample_correctmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
    n_maxsamples = 8
    n_labels = len(sortedBuckets)

    # size of each sample
    fig = plt.figure(figsize=(n_maxsamples * 1.8, n_labels))
    w_ratios = [1 for n in range(n_maxsamples)]
    w_ratios[:0] = [int(n_maxsamples * 0.8)]
    h_ratios = [1 for n in range(n_labels)]

    # gridspec
    time.sleep(1)  # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_maxsamples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
                             height_ratios=h_ratios)
    labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
    row = 1
    for i, a in enumerate(labelset_pbar):
        cclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['correct']
        pclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['predicted']
        cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
        pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
        count = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['count']
        for b in range(n_maxsamples + 1):
            i = a * (n_maxsamples + 1) + b
            ax = plt.Subplot(fig, grid[i])
            if b == 0:
                ax.annotate(
                    '%d, CClassId %d (%d): %s\nPClassId %d: %s' % (row, cclassId, count, cdescription, pclassId, pdescription),
                    xy=(0, 0), xytext=(0.0, 0.3))
                row += 1
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)
            else:
                if (b - 1) < count:
                    image = dataset[incorrectmatrix[sortedBuckets[n_labels - a - 1]]['samples'][b - 1]]
                    if cmap == None:
                        ax.imshow(image)
                    else:
                        # yuv = cv2.split(image)
                        # ax.imshow(yuv[0], cmap=cmap)
                        ax.imshow(image, cmap=cmap)
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)

        # hide the borders\
        if a == (n_labels - 1):
            all_axes = fig.get_axes()
            for ax in all_axes:
                for sp in ax.spines.values():
                    sp.set_visible(False)

    plt.show()
    
draw_sample_correctmatrix('prediction images (RGB)', sortedBuckets, incorrectmatrix, newimages)
prediction images (RGB): 100%|██████████| 17/17 [00:03<00:00,  4.86labels/s]

Analyze Performance

In [93]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [14]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

with tf.Session() as sess:
    TOPKV = sess.run(tf.nn.top_k(tf.constant(y_new_onehot), k=5))
In [25]:
np.set_printoptions(precision=4)
np.set_printoptions(suppress=True)
print(TOPKV[0])
print(TOPKV[1])
[[0.6951 0.139  0.0478 0.0173 0.0108]
 [0.9995 0.0001 0.     0.     0.    ]
 [0.9994 0.0001 0.0001 0.     0.    ]
 [0.7362 0.0651 0.0231 0.0221 0.0177]
 [0.8126 0.1016 0.0546 0.0053 0.0032]
 [0.4502 0.085  0.0717 0.0563 0.0366]
 [0.8986 0.0307 0.0156 0.0098 0.0089]
 [0.2153 0.1856 0.0633 0.0465 0.0432]
 [0.5059 0.1831 0.1071 0.035  0.0292]
 [0.52   0.0764 0.0507 0.0463 0.0361]
 [0.999  0.0001 0.0001 0.0001 0.0001]
 [0.9847 0.0019 0.0018 0.0016 0.0013]
 [0.8338 0.0217 0.0152 0.0109 0.0108]
 [0.8999 0.0137 0.0076 0.0056 0.0044]
 [0.9206 0.0071 0.0067 0.0051 0.004 ]
 [0.9983 0.0003 0.0001 0.0001 0.0001]
 [0.9994 0.0001 0.0001 0.     0.    ]
 [0.9993 0.0001 0.0001 0.0001 0.    ]
 [0.9895 0.0024 0.0012 0.0008 0.0006]
 [0.9996 0.     0.     0.     0.    ]]
[[17 12 10 14 13]
 [14 24 17 27 19]
 [14 17 24 27 19]
 [14 15  1 12 13]
 [40 39 38 12 34]
 [18 35  1 13 15]
 [30 23 20 29 31]
 [33 40  9 38 41]
 [34 35 38 36 40]
 [13 32 41 26 12]
 [28 19 26  6 27]
 [29 28  3 22  0]
 [13 42 26 30 12]
 [13 10 26  3 42]
 [13 10 12 26 11]
 [26 11 13 20 18]
 [25 27 28 23 26]
 [17 14 21 16 37]
 [17 14 11 10 26]
 [18 32 26 16  6]]
In [ ]:
n_labels = 43
newlabels = []
for i in range(n_labels):
    newlabels.append(i)
ind = np.arange(n_labels)
    

    # gridspec
    time.sleep(1)  # wait for 1 second for the previous print to appear!
    grid = gridspec.GridSpec(n_labels, n_maxsamples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
                             height_ratios=h_ratios)
In [61]:
w_ratios[:0] = [int(8 * 0.8)]
print(w_ratios)
[6, 1, 1, 1, 1, 1, 1, 1, 1]
In [90]:
fig = plt.figure(figsize=(20, len(newimages)))

w_ratios = [2, 2, 6]
h_ratios = [1 for n in range(len(newimages))]
grid = gridspec.GridSpec(ncols=3, nrows=len(newimages), wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
labelset_pbar = tqdm(range(len(newimages)), desc='Softmax Probabity', unit='labels')
time.sleep(1)  # wait for 1 second for the previous print to appear!

np.set_printoptions(precision=2)
np.set_printoptions(suppress=True)

for a in labelset_pbar:
    for b in range(3):
        ax = fig.add_subplot(grid[a, b])
        if b == 0:
            x = TOPKV[0][a]
            y = TOPKV[1][a]
            anno_txt = ('  '.join(['%.2f']*len(x))+"]") % tuple(x) + '\n ' + ('  '.join(['%4d']*len(y))+"]") % tuple(y)
            ax.annotate(anno_txt,xy=(0, 0), xytext=(0.0, 0.3))
            ax.set_xticks([])
            ax.set_yticks([])
            fig.add_subplot(ax)
        elif b == 1:
            image = newimages[a]
            ax.imshow(image)
            ax.set_xticks([])
            ax.set_yticks([])
            fig.add_subplot(ax)
        elif b == 2:
            # fg, ax = plt.subplots(figsize=(n_labels/3, 3))
            p1 = ax.bar(ind*1.15+0.75, y_new_onehot[a], width, color='b')
            # add some text for labels, title and axes ticks
            ax.set_ylim(0, 1)
            #ax.set_title("Softmax Probabilities", fontsize=12)
            #ax.set_xticks(ind*1.15 + 1.0)
            #ax.set_xticklabels(newlabels, fontsize=10)
            #ax.set_xlabel("Class Id", fontsize=12)
            fig.add_subplot(ax, figsize=(n_labels/3, 3))
    
plt.show()
Softmax Probabity: 100%|██████████| 20/20 [00:03<00:00,  6.45labels/s]

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [6]:
first_conv_output = model.get_intermediate_output(new_image)[0]
In [14]:
activation = first_conv_output
activation_min = activation.min()
activation_max = activation.max()
In [18]:
featuremaps = activation.shape[3]
plt_num=8
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
    plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
    plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
    plt.imshow(activation[-1,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
In [16]:
activation_max
Out[16]:
3.5072045